# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
import os
import re

from stanfordcorenlp import StanfordCoreNLP

nlp = StanfordCoreNLP(r'D:\stanford-corenlp-4.1.0', lang='en')


def get_files(pathname):
    filenames = []
    for root, dirs, files in os.walk(pathname):
        for file in files:
            filenames.append(os.path.join(root, file))
    print('----- Get Files Down. -----')

    return filenames


def _get_tokens(sentence):
    try:
        tokens = nlp.word_tokenize(sentence)
    except:
        tokens = []

    return tokens


def _get_context(filename):
    context = ''
    with open(filename, 'rb') as f:
        for line in f.readlines():
            try:
                line = re.sub(r'\s|\t|\r|\n', ' ', line.decode('utf-8'))
                context += line
            except UnicodeDecodeError:
                pass
    tokens = _get_tokens(context)
    # 为了适配更少的代码，因此用空格拼接
    context = ' '.join(tokens)

    return context


def _get_label(filename):
    file_types = {
        'comp': '0',
        'politics': '1',
        'rec': '2',
        'religion': '3'
    }
    for key, label in file_types.items():
        if key in filename:
            return label

    return ''


def _load_data(filenames):
    total_data = []
    for filename in filenames:
        context = _get_context(filename)
        label = _get_label(filename)
        if label:
            total_data.append(context + '\t' + label)
    print('----- Load Data Down. -----')

    return total_data


def load_data(filepath):
    filenames = get_files(filepath)
    data = _load_data(filenames)
    return data


def save_data(filename, data):
    with open(filename, 'w') as f:
        for line in data:
            try:
                f.write(line + '\n')
            except:
                pass
    print('----- Write Down. -----')


def main():
    train_path = r'D:\Dataset\RCNN_news\20news-bydate-train'
    test_path = r'D:\Dataset\RCNN_news\20news-bydate-test'

    train_data = load_data(train_path)
    test_data = load_data(test_path)

    save_data('train.txt', train_data)
    save_data('test.txt', test_data)


if __name__ == '__main__':
    main()
